/**
 * 
 */
package kr.co.insoft.auth.repository.mail.impl;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import kr.co.insoft.auth.repository.mail.VelocityEmailSender;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 * 
 */
@Component
public class VelocityEmailSenderImpl implements VelocityEmailSender {

	private VelocityEngine velocityEngine;
	private JavaMailSender mailSender;

	/**
	 * Sends e-mail using Velocity template for the body and the properties
	 * passed in as Velocity variables.
	 * 
	 * @param msg
	 *            The e-mail message to be sent, except for the body.
	 * @param hTemplateVariables
	 *            Variables to use when processing the template.
	 */
	@Override
	public void send(final SimpleMailMessage msg,
			final Map<String, Object> hTemplateVariables) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
				message.setTo(msg.getTo());
				message.setFrom(msg.getFrom());
				message.setSubject(msg.getSubject());
				String body = VelocityEngineUtils.mergeTemplateIntoString(
						velocityEngine,
						"registration-confirmation.vm",
						"UTF-8", hTemplateVariables);
				message.setText(body, true);
			}
		};
		mailSender.send(preparator);
	}

	/**
	 * @param velocityEngine
	 *            the velocityEngine to set
	 */
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	/**
	 * @param mailSender
	 *            the mailSender to set
	 */
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
}
